﻿using System;
using System.Linq;

using TempEmployees.DAL;
using TempEmployees.BLL.Database;

namespace TempEmployees.BLL.EntitiesExtensions
{
    public static class EUser
    {
        public static User GetUserById(string userId)
        {
            TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext(); 
            var user = db.Users.Where((u) => u.ID == userId);
            return (user.Count() == 1) ? user.First() : null;
        }

        public static UserRole GetUserRoles(this User user)
        {
            return new UserRole(user.Roles);
        }

        public static void UpdateUser(User user, int departmentId, bool insert = true)
        {
            User dbUser = GetUserById(user.ID);
            if (dbUser != null)
            {
                if (!string.IsNullOrEmpty(dbUser.Password)) return;
                DbQuery.Update<User>(user, dbUser);
            }
            else if (insert)
            {
                DbQuery.Insert<User>(user);
            }

            if (departmentId > 0)
            {
                UserDepartment ud = DbQuery.GetSingleRow<UserDepartment>("UserID", user.ID);
                if (ud == null)
                {
                    ud = new UserDepartment(user.ID, departmentId);
                    DbQuery.Insert<UserDepartment>(ud);
                }
                else
                {   
                    UserDepartment newUD = new UserDepartment(user.ID, departmentId);
                    newUD.ID = ud.ID;
                    DbQuery.Update<UserDepartment>(newUD, ud);
                }
            }
        }
    }
}
